/*
@authors - Siddharth Sathyam, Pat LaMontagna, Alan Ruvalcaba
@Description - Chat Window GUI Code
**/

#include "im_window.h"
#include "ui_im_window.h"
#include "QDebug"

im_window::im_window(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::im_window)
{
    ui->setupUi(this);
}

void im_window::setSocket(QTcpSocket* soc)
{
    // Set the mainSoc to the new window (pass from the Login Window to the IM Window)
    mainSoc = soc;
    connect(mainSoc, SIGNAL(readyRead()), this, SLOT(readyRead()));
}

im_window::~im_window()
{
    delete ui;
}

void im_window::readyRead()
{
    QDataStream recvStream(mainSoc);
    recvStream.setVersion(QDataStream::Qt_4_0);
    quint16 packId;
    quint16 blockSize = 0;

    // read in data from the socket in accordance with the protocol that was decided

    if(blockSize == 0)
    {
	if(mainSoc->bytesAvailable() < sizeof(quint16))
	{
	    return;
	}
	recvStream >> packId;
	// if the header = 1 then server sent us a message from another user
	if(packId == 1)
	{
	    QString toUser;
	    QString fromUser;
	    QString timeSent;
	    QString message;

	    // Break up the message into its individual parts and save it to the variables
	    recvStream >> fromUser >> toUser >> message >> timeSent;
	    ui->messageWindow->append(timeSent + ": " + fromUser + " - " + message + "\n");
	}
	// if the header = 2 then server sent us a list of updated users
	else if(packId == 2)
	{
	    QStringList listOfUsers;
	    recvStream >> listOfUsers;
	    updateUsersList(listOfUsers);
	}
    }
}

// Send the message with the header, the fromUserName, the toUsername, the message, and the time msg was sent at
void im_window::sendMessage(QString fromUsername, QString toUsername, QString message, QString timeSent)
{
    QByteArray datablock;
    QDataStream sendStream(&datablock , QIODevice::WriteOnly);
    sendStream.setVersion(QDataStream::Qt_4_0);

    // message header 1 is intrepeted by the server as a message with to and from userNames
    sendStream << quint16(1) << (QString) fromUsername << (QString) toUsername << (QString) message << (QString) timeSent;
    mainSoc->write(datablock);

    ui->messageWindow->append(timeSent + ": "+ fromUsername + " - " + message + "\n");
}

// Message gets sent when the send button is clicked in the client
void im_window::on_sendButton_clicked()
{
    QList <QListWidgetItem*> selectedItemList = ui->listOfUsers->selectedItems();
    if(!selectedItemList.empty())
    {
	// Get first element of the selected items list - Cast it as an QString since it was inserted into the
	// list view as QStrings
	QListWidgetItem* listItem = (QListWidgetItem*) selectedItemList.front();
	QString recipient = listItem->text();
	if(recipient.isNull())
	{
	    // @TODO display error window, error in casting
	}

	QString message = (QString) ui->textEnter->toPlainText();

	if(!message.isEmpty() && !message.isNull())
	{
	    sendMessage(clientUserName, recipient , message, QTime::currentTime().toString(Qt::TextDate));
	    ui->textEnter->clear();
	}
	else
	{
	    // @TODO Message Box is empty or invalid - Add code here to display error window
	}
    }
    else
    {
	// @TODO recipient is empty or invalid - Add code here to display error window
    }
}


void im_window::setUserName(QString name)
{
    if(!name.isEmpty() && !name.isNull())
    {
	clientUserName = name;
	ui->chatHeader->setText("Hello " + clientUserName);
    }
}

// Updates the list of users in client
void im_window::updateUsersList(QStringList list)
{
    ui->listOfUsers->clear();

    foreach (QString name, list)
    {
	if(name != clientUserName)
	{
	    ui->listOfUsers->addItem(name);
	}
    }
}
